package com.example.controlexercise;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class okHttpAndJson extends AppCompatActivity {

    public TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ok_http_and_json);
    }

    public void sendRequest(View view) {
        useOkHttp2("https://csdn.net", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showMessage("网络访问失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                showMessage(response.body().string());
            }
        });
    }

    public void useOkHttp2(String path,Callback callback){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(path).build();
        okHttpClient.newCall(request).enqueue(callback);

    }



    public void showMessage(String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                textView.setText(response);
            }
        });
    }


}
